const RecordInfo = require("../models/RecordInfo");
const sequelize = require("../models/db");
const { Op } = require("sequelize");
const { showByArrs } = require("../tools");
module.exports = class RecordManager {
  /**
   * 增加一个Record
   * @param {*} obj
   * @returns
   */
  static async add(obj) {
    const result = await RecordInfo.create(obj);
    return result.toJSON();
  }
  /**
   * 批量新增Record
   * @param {*} obj
   * @returns
   */
  static async bulkCreate(valueArr) {
    const result = await RecordInfo.bulkCreate(valueArr);
    return result;
  }
  /**
   * 同步病人端未检查的数据到医生端
   * @param {*} val
   */
  // static async synchronization(val) {
  //   const _this = this;
  //   console.log("+++++++++++++++++++val", val.length);
  //   const needAddP = []; //需要添加的病人
  //   const needAddR = []; //需要添加的记录
  //   let promises;

  //   if (val.length > 0) {
  //     promises = val.map(async (item) => {
  //       //如果有就跳出
  //       const record = await _this.getById(item.id);
  //       console.log("record", record);
  //       if (record) {
  //         return [];
  //       } else {
  //         console.log("myjcr", record);
  //         //没有就插入
  //         if (item.patientinfo) {
  //           const p = await PatirntServer.getById(item.patientinfo.id);

  //           if (!p) {
  //             let newItem = { ...item.patientinfo };
  //             delete newItem.createdAt;
  //             delete newItem.updatedAt;
  //             delete newItem.deletedAt;

  //             needAddP.push(newItem);
  //           } else {
  //             let updateItem = {
  //               name: item.patientinfo.name ? item.patientinfo.name : "",
  //               sex: item.patientinfo.sex,
  //               birth: item.patientinfo.birth ? item.patientinfo.birth : "",
  //               year: item.patientinfo.year,
  //               tel: item.patientinfo.tel ? item.patientinfo.tel : "",
  //               addr: item.patientinfo.addr ? item.patientinfo.addr : "",
  //             };
  //             PatirntServer.update(item.patientinfo.id, updateItem);
  //           }
  //         }
  //         let newRecordInfo = { ...item };
  //         delete newRecordInfo.createdAt;
  //         delete newRecordInfo.updatedAt;
  //         delete newRecordInfo.deletedAt;
  //         delete newRecordInfo.patientinfo;

  //         needAddR.push(newRecordInfo);
  //       }
  //     });

  //     await Promise.all(promises);

  //     //去重
  //     const uniqueP = [];
  //     const obj = {};
  //     for (var i = 0; i < needAddP.length; i++) {
  //       if (!obj[needAddP[i].id]) {
  //         uniqueP.push(needAddP[i]);
  //         obj[needAddP[i].id] = true;
  //       }
  //     }
  //     console.log("++++++++++++++++++++++++++uniqueP", uniqueP);
  //     // console.log("needAddR", needAddR);

  //     const addPres = await PatirntServer.bulkCreate(uniqueP);

  //     console.log("+++++++++++++++++++++addPres", addPres);

  //     const addRres = await _this.bulkCreate(needAddR);

  //     // console.log("addRres", addRres);

  //     return "成功";
  //   } else {
  //     return [];
  //   }
  // }

  /**
   * 删除一个Record
   * @param {*} id
   */
  static async delete(id) {
    const result = await RecordInfo.destroy({
      where: {
        id,
      },
    });
  }

  /**
   * 批量删除Record
   * @param {*} id
   */
  static async bulkDelete(params) {
    let promises;
    const _this = this;
    const delRes = [];

    if (params.length > 0) {
      promises = params.map(async (item) => {
        const res = await _this.delete(item);
        delRes.push(res);
      });
    }
    await Promise.all(promises);
  }

  /**
   * 根据state批量删除Record
   * @param {*} state
   */
  static async bulkDeleteByState() {
    const result = await RecordInfo.destroy({
      where: {
        state: 0,
      },
    });

    return result;
  }

  /**
   * 更新Record
   * @param {*} Id
   * @param {*} Obj
   */
  static async update(Id, obj) {
    const result = await RecordInfo.update(obj, {
      where: {
        id: Id,
      },
    });
    return result;
  }

  /**
   * 查询所有的Record
   * @returns
   */
  static async getAll() {
    const result = await RecordInfo.findAll();
    return JSON.parse(JSON.stringify(result));
  }

  /**
   * 根据id查询Record
   * @returns
   */
  static async getById(id) {
    const result = await RecordInfo.findOne({
      where: {
        id,
      },
    });
    if (result === null) {
      console.log("Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }

  /**
   * 根据id查询Record
   * @returns
   */
  static async getByIdAndPatient(id) {
    const result = await RecordInfo.findOne({
      where: {
        id,
      },
    });
    if (result === null) {
      console.log("Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }

  /**
   * 分页查询Record
   * @returns
   */
  static async find(page = 1, limit = 10) {
    const result = await RecordInfo.findAndCountAll({
      offset: (page - 1) * limit,
      limit: +limit,
    });
    if (result === null) {
      console.log("Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }

  /**
   * 连表分页查询Record
   * @returns
   */
  static async findRecordAndPatientInfo(
    page = 1,
    limit = 10,
    pat_hospital,
    doc_hospital,
    name,
    pos,
    doctor_sn,
    patient_sn,
    createdAt,
    model,
    state,
    sNo,
    sex
    // realModel
  ) {
    let recorfWhere = {};
    if (name) {
      recorfWhere.name = {
        [Op.like]: `%${name}%`,
      };
    }
    if (pat_hospital) {
      recorfWhere.pat_hospital = {
        [Op.like]: `%${pat_hospital}%`,
      };
    }
    if (doc_hospital) {
      recorfWhere.doc_hospital = {
        [Op.like]: `%${doc_hospital}%`,
      };
    }
    if (pos) {
      recorfWhere.pos = {
        [Op.like]: `%${pos}%`,
      };
    }
    // if (doctor_sn && !patient_sn) {
    //   recorfWhere.doctor_sn = {
    //     [Op.like]: `%${doctor_sn}%`,
    //   };
    // } else if (!doctor_sn && patient_sn) {
    //   recorfWhere.patient_sn = {
    //     [Op.like]: `%${patient_sn}%`,
    //   };
    // } else if (doctor_sn && patient_sn) {
    //   recorfWhere = {
    //     ...recorfWhere,
    //     [Op.or]: [{ patient_sn: patient_sn }, { doctor_sn: doctor_sn }],
    //   };
    // }
    if (doctor_sn && !patient_sn) {
      console.log("+++++++++++Array.isArray doctor_sn",Array.isArray(doctor_sn))
      if(Array.isArray(doctor_sn)){
        recorfWhere.doctor_sn = {
          [Op.or]: doctor_sn,
        };
      }else{
        recorfWhere.doctor_sn = {
          [Op.like]: `%${doctor_sn}%`,
        };
      }
    } else if (!doctor_sn && patient_sn) {
      console.log("+++++++++++Array.isArray patient_sn",Array.isArray(patient_sn))
      if(Array.isArray(patient_sn)){
        recorfWhere.patient_sn = {
          [Op.or]: patient_sn,
        };
      }else{
        recorfWhere.patient_sn = {
          [Op.like]: `%${patient_sn}%`,
        };
      }
    } else if (doctor_sn && patient_sn) {
      console.log("boths ",Array.isArray(patient_sn),Array.isArray(doctor_sn))
      recorfWhere = {
        ...recorfWhere,
        [Op.or]: [{ patient_sn: patient_sn }, { doctor_sn: doctor_sn }],
      };
    }
    if (model) {
      recorfWhere.model = {
        [Op.like]: `%${model}%`,
      };
    }
    if (typeof state == "number") {
      recorfWhere.state = {
        [Op.like]: `%${state}%`,
      };
    }
    if (sNo) {
      recorfWhere.sNo = {
        [Op.like]: `%${sNo}%`,
      };
    }
    if (sex == 1 || sex == 0) {
      recorfWhere.sex = {
        [Op.like]: `%${sex}%`,
      };
    }
    // if(realModel){
    //   recorfWhere.realModel = {
    //     [Op.or]: [realModel, null]
    //   }
    // }
    if (createdAt) {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      let day = new Date().getDay();
      let h = new Date().getHours();
      let m = new Date().getHours();
      let s = new Date().getSeconds();
      if (month < 10) {
        month = `0${month}`;
      }
      if (day < 10) {
        day = `0${day}`;
      }
      if (h < 10) {
        h = `0${h}`;
      }
      if (m < 10) {
        m = `0${m}`;
      }
      if (s < 10) {
        s = `0${s}`;
      }
      const start = `${createdAt[0]} 00:00:00`;
      let end;
      if (createdAt[0] != createdAt[1]) {
        if (createdAt[1] == `${year}-${month}-${day}`) {
          end = `${createdAt[1]} ${h}:${m}:${s}`;
        } else {
          end = `${createdAt[1]} 23:59:59`;
        }
        recorfWhere.createdAt = {
          [Op.between]: [start, end],
        };
      } else {
        if (start != `${year}-${month}-${day}`) {
          end = `${createdAt[0]} 23:59:59`;
        } else {
          end = `${createdAt[0]} ${h}:${m}:${s}`;
        }
        recorfWhere.createdAt = {
          [Op.between]: [start, end],
        };
      }
      console.log("++++++++++++++++++++++++++++", start);
      console.log("++++++++++++++++++++++++++++", end);
    }
    const result = await RecordInfo.findAndCountAll({
      where: recorfWhere,
      attributes: [
        "id",
        "sNo",
        "name",
        "sex",
        "birth",
        "year",
        "tel",
        "addr",
        "pos",
        "height",
        "weight",
        "chief",
        "his",
        "date",
        "time",
        "images",
        "movies",
        "state",
        "seen",
        "tips",
        "seenData",
        "reportimg",
        "choseImg",
        "videos",
        "doctor_sn",
        "patient_sn",
        "hospitalInfo",
        "doc_hospital",
        "pat_hospital",
        "model",
        "pat_alias",
        "createdAt"
      ],
      offset: (page - 1) * limit,
      limit: +limit,
      order: [["createdAt", "DESC"]],
    });
    if (result === null) {
      console.log("Not found!");
    } else {
      const res = JSON.parse(JSON.stringify(result));
      const showres = showByArrs(res, [
        "id",
        "sNo",
        "name",
        "sex",
        "birth",
        "year",
        "tel",
        "addr",
        "pos",
        "height",
        "weight",
        "chief",
        "his",
        "data",
        "images",
        "movies",
        "state",
        "seen",
        "tips",
        "seenData",
        "choseImg",
        "videos",
        "doctor_sn",
        "patient_sn",
        "doc_hospital",
        "pat_hospital",
        "model",
        "pat_alias",
        "measureInfo",
      ]);
      console.log("res", showres);
      return res;
    }
  }

  /**
   * 连表查询未检查的病人及信息
   * @returns
   */
  static async findNoCheckedRecord() {
    const result = await RecordInfo.findAll({
      where: {
        state: 0,
      },
    });
    return result;
  }

  /**
   * test
   * @returns
   */
  static async test() {
    const result = await RecordInfo.findAll({
      attributes: {
        include: [[sequelize.fn("COUNT", sequelize.col("chief")), "n_chiefs"]],
      },
    });
    if (result === null) {
      console.log("Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }
};
